package main

import (
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup
var once sync.Once
func job(id int, jobs chan<- int) {
	defer wg.Done()
	fmt.Printf("start job:%d\n", id)
	jobs <- id
	fmt.Printf("end job:%d\n", id)
	//close(jobs)
	//once.Do(func() { close(jobs) })
}
func worker(id int, jobs <-chan int, results chan<- int) {
	defer wg.Done()
	for j := range jobs {
		fmt.Printf("worker:%d start job:%d\n", id, j)
		time.Sleep(time.Second)
		fmt.Printf("worker:%d end job:%d\n", id, j)
		results <- j
	}


	//for {
	//	tmp, ok := <- jobs
	//	if !ok {
	//		break
	//	}
	//	fmt.Printf("worker:%d start job:%d\n", id, tmp)
	//	time.Sleep(time.Second)
	//	fmt.Printf("worker:%d end job:%d\n", id, tmp)
	//	results <- tmp
	//}
}

func main() {
	jobs := make(chan int, 100)
	results := make(chan int, 100)
	// 开启3个goroutine
	wg.Add(3)
	for c := 1; c <= 3; c++ {
		go worker(c, jobs, results)
	}
	// 5个任务
	wg.Add(100)
	for s := 1; s <= 100; s++ {
		go job(s, jobs)
	}

	// 输出结果
	//for a := 1; a <= 5; a++ {
	//	fmt.Printf("job:%d完成!!! \n", <-results)
	//}
	for tmp := range results {
		fmt.Printf("job:%d完成!!! \n", tmp)
	}
	close(jobs)
	//close(results)
	wg.Wait()
}
